<?php

namespace addons\shopro\model\commission;

use addons\shopro\model\User;

use think\Model;

class Order extends Model
{
    const COMMISSION_ORDER_STATUS_NO = 0;  // 不计入
    const COMMISSION_ORDER_STATUS_YES = 1;  // 已计入
    const COMMISSION_ORDER_STATUS_BACK = -1;  // 已退回
    const COMMISSION_ORDER_STATUS_CANCEL = -2;  // 已取消
    // 表名
    protected $name = 'shopro_commission_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    protected $append = [
        'commission_order_status_text',
        // 'commission_reward_status_text',
    ];
    public static function maskPhoneNumber($phone) {
        $length = 4; // 需要替换的星号长度，这里是4位
        // 计算需要替换的起始位置
        $start = (strlen($phone) - $length) / 2;
         
        // 使用substr_replace替换中间的数字为星号
        $maskedPhone = substr_replace($phone, str_repeat('*', $length), $start, $length);
         
        return  $maskedPhone; // 输出：1234****901
    }
    public static function getRanking($params){
        extract($params);
        $params['type'] = 'yes';
        if($date_type == 0){
            // 今天
            $params['date'] = date("Y/m/d")."-".date("Y/m/d");
        } else if($date_type == 1){
            // 本周
            $monday = strtotime("Monday this week");
            $monday = date('Y/m/d', $monday);
            $sunday = strtotime("Sunday this week");
            $sunday = date('Y/m/d', $sunday);
            $params['date'] = $monday."-".$sunday;
        } else {
            // 本月
            $start = date('Y/m/01');
            $end = date('Y/m/t');
            $params['date'] = $start."-".$end;
        }
        if($order_type == 0){ //个人订单
            $list = self::buildSearch($params)->group("agent_id")->field('agent_id, COUNT(*) as order_count')->order('order_count', 'desc')->select();
        } else {
            //获取所有代理(经理)
            $agentModel = new Agent();
            $level = $order_type == 1 ? 3 : 2;
            $agents_ids_3 = Agent::where("level",$level)->where("pay_status",1)->column("user_id");
            $agent_ids = self::buildSearch($params)->whereIn("agent_id",$agents_ids_3)->column("agent_id");
            $agent_ids = array_unique($agent_ids);
            $agent_ids = array_values($agent_ids);
            $list = [];
            for($i = 0;$i < count($agent_ids);$i++){
                $child_res = $agentModel->getChild($agent_ids[$i]);
                $child_res['child'][] = $agent_ids[$i];
                $params['agent_id'] = $child_res['child'];
                $order_count = self::buildSearch($params)->count();
                if($order_count > 0){
                    $list[] = ["agent_id"=>$agent_ids[$i],"order_count"=>$order_count];
                }
            }
            usort($list, function($a, $b) {
                return $b['order_count'] <=> $a['order_count'];
            });
        }
        $agents = [];
        for($i = 0;$i < count($list);$i++){
            $agent = Agent::where("user_id",$list[$i]['agent_id'])->find();
            $apply_info = '';
            if($agent){
                $apply_info = json_decode($agent['apply_info'],true);
                $apply_info_new = [];
                for($j = 0;$j < count($apply_info);$j++){
                    $apply_info_new[$apply_info[$j]['key']] = $apply_info[$j]['value'];
                }
                $apply_info = $apply_info_new;
            }
            $user = User::where("id",$list[$i]['agent_id'])->field("id,avatar,nickname")->find()->toArray();
            $user['nickname'] = mb_substr($user['nickname'], 0, 1)."**";
            $apply_info['mobile'] = self::maskPhoneNumber($apply_info['mobile']);
            $agents[] = [
                "user" => $user,
                "order_count" => $list[$i]['order_count'],
                'apply_info' => $apply_info,
            ];
        }
       return $agents;
    }
    public static function statistics($params){
        extract($params);
        if(!isset($agentId) || !$agentId){
            $user = User::info();
            $agentId = $user->id;
        }
        $agentModel = new Agent();
        $child_res = $agentModel->getChild($agentId);
        extract($child_res);
        $params['type'] = 'yes';
        $result = [];
        $child[] = $agentId;
        if(isset($params['cat']) && $params['cat'] == 1){
            $params['type'] = 'accounted';
            $result['user'] = User::get($agentId);
            $agent = $agentModel::with("level")->where("user_id",$agentId)->find();
            if($agent){
                $apply_info = json_decode($agent['apply_info'],true);
                $apply_info_new = [];
                for($i = 0;$i < count($apply_info);$i++){
                    $apply_info_new[$apply_info[$i]['key']] = $apply_info[$i]['value'];
                }
                $agent['apply_info'] = $apply_info_new;
            }
            $result['agent'] = $agent;
            $params['agent_id'] = $child;
            // 今天
            $params['date'] = date("Y/m/d")."-".date("Y/m/d");
            $result['today_order_count'] = self::buildSearch($params)->count();
            $result['today_order_money'] = Reward::buildSearchNew($params)->sum("commission");
            // 昨天
            $yesterday = date("Y/m/d", strtotime("-1 day"));
            $params['date'] = $yesterday."-".$yesterday;
            $result['yesterday_order_count'] = self::buildSearch($params)->count();
            $result['yesterday_order_money'] = Reward::buildSearchNew($params)->sum("commission");
            // 本周
            $monday = strtotime("Monday this week");
            $monday = date('Y/m/d', $monday);
            $sunday = strtotime("Sunday this week");
            $sunday = date('Y/m/d', $sunday);
            $params['date'] = $monday."-".$sunday;
            $result['week_order_count'] = self::buildSearch($params)->count();
            $result['week_order_money'] = Reward::buildSearchNew($params)->sum("commission");
            // 本月
            $start = date('Y/m/01');
            $end = date('Y/m/t');
            $params['date'] = $start."-".$end;
            $result['month_order_count'] = self::buildSearch($params)->count();
            $result['month_order_money'] = Reward::buildSearchNew($params)->sum("commission");
        } else {
            // 团队订单
            $params['agent_id'] = $child;
            $result['child_order_count'] = self::buildSearch($params)->count();
            $result['child_order_money'] = self::buildSearch($params)->sum("amount");
            $params['agent_id'] = $child_1;
            $result['child_order_count_1'] = self::buildSearch($params)->count();
            $result['child_order_money_1'] = self::buildSearch($params)->sum("amount");
            $params['agent_id'] = $child_2;
            $result['child_order_count_2'] = self::buildSearch($params)->count();
            $result['child_order_money_2'] = self::buildSearch($params)->sum("amount");
            $params['agent_id'] = [$agentId];
            $result['order_count'] = self::buildSearch($params)->count();
            $result['order_money'] = self::buildSearch($params)->sum("amount");
        }
        return $result;
    }
    /**
     * 获取分销订单明细
     *
     * @return array
     */
    public static function getList($params)
    {
        extract($params);
        if(!isset($agentId) || !$agentId){
            $user = User::info();
            $agentId = $user->id;
        }
        $params['agent_id'] = [$agentId];
        // 获取佣金记录
        $oldModes = closeStrict(['ONLY_FULL_GROUP_BY']);
        $orders = self::buildSearch($params)->field('id, order_id, buyer_id')->with(['buyer', 'order', 'commission_order' => function ($query) use($agentId){
            $query->with(['order_item', 'reward' =>function($query) use($agentId) {
                $query->where('agent_id', $agentId);
            }]);
        }])->group('order_id')->order('id', 'desc')->paginate($per_page ?? 10);

        recoverStrict($oldModes);

        // 获取查询条件的总佣金
        $type = $type ?? 'all';
        if ($type == 'all') {
            // 收入，包含待入账
            $amount = self::buildSearch($params)->yes()->sum('amount');
        } else {
            $amount = self::buildSearch($params)->sum('amount');
        }

        return [
            'orders' => $orders,
            'amount' => $amount,
        ];
    }


    /**
     * 构建查询条件
     */
    private static function buildSearch($params)
    {
        extract($params);
        $date = isset($date) ? explode('-', $date) : [];
        $start = isset($date[0]) ? strtotime($date[0]." 00:00:00") : strtotime(date('Y-m') . '-01 00:00:00');
        $end = isset($date[1]) ? (strtotime($date[1]." 23:59:59")) : strtotime(date('Y-m-d')." 23:59:59");
        if(isset($params['agent_id']) && $params['agent_id']){
            $rewards = self::whereIn('agent_id', $params['agent_id']);
        } else {
            $rewards = self::where("1=1");
        }
        $type = $type ?? 'all';
        if ($type != 'all' && in_array($type, ['yes', 'back', 'cancel'])) {
            $rewards = $rewards->{$type}();
        }

        $rewards = $rewards->whereBetween('createtime', [$start, $end]);
        
        return $rewards;
    }

    /**
     * 已计入
     */
    public function scopeYes($query)
    {
        return $query->where('commission_order_status', self::COMMISSION_ORDER_STATUS_YES);
    }

    /**
     * 已退回
     */
    public function scopeBack($query)
    {
        return $query->where('commission_order_status', self::COMMISSION_ORDER_STATUS_BACK);
    }

    /**
     * 已取消
     */
    public function scopeCancel($query)
    {
        return $query->where('commission_order_status', self::COMMISSION_ORDER_STATUS_CANCEL);
    }

    /**
     * 不计入
     */
    public function scopeNo($query)
    {
        return $query->where('commission_order_status', self::COMMISSION_ORDER_STATUS_NO);
    }

    public function buyer()
    {
        return $this->belongsTo(\addons\shopro\model\User::class, 'buyer_id')->field('id, avatar, nickname');
    }

    public function order()
    {
        return $this->belongsTo(\addons\shopro\model\Order::class, 'order_id')
            ->field('id, order_sn, activity_type, status, ext, createtime');
    }

    public function commissionOrder()
    {
        return $this->hasMany(Order::class, 'order_id', 'order_id');
    }

    public function reward()
    {
        return $this->hasOne(\addons\shopro\model\commission\Reward::class, 'commission_order_id');
    }

    public function orderItem()
    {
        return $this->belongsTo(\addons\shopro\model\OrderItem::class, 'order_item_id')->field('id,user_id,order_id,goods_id,goods_title, goods_sku_text,goods_image,goods_original_price,goods_price,goods_num,refund_status,comment_status,aftersale_status,dispatch_status,dispatch_type');
    }

    public function getCommissionOrderStatusTextAttr($value, $data)
    {
        $status_name = '';

        if (isset($data['commission_order_status'])) {
            switch ($data['commission_order_status']) {
                case self::COMMISSION_ORDER_STATUS_NO:
                    $status_name = '不计入';
                    break;
                case self::COMMISSION_ORDER_STATUS_YES:
                    $status_name = '已计入';
                    break;
                case self::COMMISSION_ORDER_STATUS_BACK:
                    $status_name = '已退回';
                    break;
                case self::COMMISSION_ORDER_STATUS_CANCEL:
                    $status_name = '已取消';
                    break;
            }
        }
        return $status_name;
    }
   
}
